/**
 * Copyright (c) 2013-2016, Jieven. All rights reserved.
 *
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt
 * To use it on other terms please contact us at 1623736450@qq.com
 */
package com.zmhz.widget;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.eova.common.base.BaseCache;
import com.eova.common.utils.xx;
import com.eova.common.utils.db.DbUtil;
import com.eova.config.EovaConfig;
import com.eova.config.EovaConst;
import com.eova.config.PageConst;
import com.eova.core.menu.config.TreeConfig;
import com.eova.engine.DynamicParse;
import com.eova.engine.EovaExp;
import com.eova.model.MetaField;
import com.eova.model.MetaObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * EOVA 控件
 *
 * @author Jieven
 *
 */
public class WidgetController extends Controller {

	/**
	 * 查找Dialog
	 */
	public void toFind() {
		render("/eova/widget/find/find.html");
	}

	

	/**
	 * Find Dialog Grid Get JSON
	 */


	/**
	 * Find get CN by value
	 */
	public void findCnByEn() {
		String code = getPara(0);
		String en = getPara(1);
		String value = getPara(2);

		// 根据表达式获取元字段
		MetaField ei = MetaField.dao.getByObjectCodeAndEn(code, en);

		String exp = ei.getStr("exp");
		// 动态解析变量和逻辑运算
		exp = DynamicParse.buildSql(exp, this.getSessionAttr(EovaConst.USER));

		// 解析表达式
		EovaExp se = new EovaExp(exp);
		String ds = se.ds;

		// 查询本次所有翻译值
		StringBuilder sb = new StringBuilder();
		if (!xx.isEmpty(value)) {
			sb.append(se.pk);
			sb.append(" in(");
			// 根据当前页数据value列查询外表name列
			for (String id : value.split(",")) {
				// TODO There might be a sb injection risk warning
				sb.append(xx.format(id)).append(",");
			}
			sb.deleteCharAt(sb.length() - 1);
			sb.append(")");
		}
		// System.out.println(sb.toString());

		// 根据表达式查询获得翻译的值
		String sql = WidgetManager.addWhere(se, sb.toString());

		List<Record> txts = Db.use(ds).find(sql);
		// 没有翻译值，直接返回原值
		if (xx.isEmpty(txts)) {
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("data", value);
			renderJson(json.toJSONString());
			return;
		}

		JSONObject json = new JSONObject();
		json.put("code", 1);
		json.put("text_field", se.cn);// 文本字段名
		json.put("data", JsonKit.toJson(txts));// 翻译字典数据
		renderJson(json.toJSONString());
	}

	/**
	 * Combo Load Data Get JSON
	 */
	public void comboJson() {
		String objectCode = getPara(0);
		String en = getPara(1);
		String exp = getPara("exp");

		List<Object> parmList = new ArrayList<Object>();

		// 构建表达式
		exp = buildExp(parmList, exp, objectCode, en);

		// 动态解析变量和逻辑运算
		exp = DynamicParse.buildSql(exp);

		// 解析表达式
		EovaExp se = new EovaExp(exp);
		String sql = se.sql;

		Object[] paras = new Object[parmList.size()];
		parmList.toArray(paras);

		List<Record> list = Db.use(se.ds).findByCache(BaseCache.SER, sql, sql, paras);
		String json = JsonKit.toJson(list);
		json = "{\"total\":" + list.size() + ",\"rows\":" + json ;
		json += "}";
		renderJson(json);
	}

	/**
	 * ComboTree Load Data Get JSON
	 */
	public void comboTreeJson() {

		String objectCode = getPara(0);
		String en = getPara(1);
		String exp = getPara("exp");

		List<Object> parmList = new ArrayList<Object>();

		// 构建表达式和参数
		exp = buildExp(parmList, exp, objectCode, en);

		// 动态解析变量和逻辑运算
		exp = DynamicParse.buildSql(exp, this.getSessionAttr(EovaConst.USER));
		EovaExp se = new EovaExp(exp);

		Object[] parms = new Object[parmList.size()];
		parmList.toArray(parms);
		List<Record> list = Db.use(se.ds).findByCache(BaseCache.SER, se.sql, se.sql, parms);

		TreeConfig treeConfig = new TreeConfig();
		treeConfig.setIdField("id");
		treeConfig.setParentField("pid");
		treeConfig.setRootPid("0");
		treeConfig.setTreeField("cn");
		treeConfig.setIconField("icon");

		// 有条件时，自动方向查找父节点数据
		if (!xx.isEmpty(se.where)) {
			// 向上查找父节点数据
			WidgetManager.findParent(treeConfig, se.ds, se.table, list, list);
		}

		renderJson(list);
	}

	/**
	 * 获取表达式
	 * @param parmList SQL动态参数
	 * @param exp 自定义表达式
	 * @param objectCode 元对象编码
	 * @param en 元字段名
	 * @return
	 */
	private String buildExp(List<Object> parmList, String exp, String objectCode, String en) {
		if (xx.isEmpty(exp)) {
			// 根据表达式获取ei
			MetaField ei = MetaField.dao.getByObjectCodeAndEn(objectCode, en);
			exp = ei.getStr("exp");
		} else {
			exp = exp.trim();
			// 预处理表达式
			try {
				String[] strs = exp.split(",");
				if (strs.length > 0) {
					exp = EovaConfig.getExps().get(strs[0]);
					for (int i = 1; i < strs.length; i++) {
						parmList.add(getSqlParam(strs[i]));
					}
				}
			} catch (Exception e) {
				throw new RuntimeException("预处理自定义查找框表达式异常，Exp=" + exp);
			}
		}
		return exp;
	}

	/**
	 * 获取SQL参数，优先Integer，不能转就当String
	 *
	 * @param str
	 * @return
	 */
	private static Object getSqlParam(String str) {
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
			return str;
		}
	}

}